<template>
    <el-drawer
        v-model="isShow"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :destroy-on-close="true"
        :show-close="false"
        :title="title"
        size="50%"
    >
        <el-form
            ref="queryFormRef"
            :model="queryForm"
            :rules="queryFormRules"
            label-position="left"
            label-width="auto"
        >
            <DividerHeader title="基本信息"/>
            <template v-if="isEdit">
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item class="image__error" label-position="top">
                            <el-image :fit="'contain'" :src="queryForm.photourl">
                                <template #error>
                                    <div class="image-slot">
                                        <el-icon>
                                            <Picture/>
                                        </el-icon>
                                        暂无证件照
                                    </div>
                                </template>
                            </el-image>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="姓名：" prop="name" required>
                            <el-input v-model="queryForm.name" placeholder="请填写来访姓名"/>
                        </el-form-item>
                        <el-form-item label="性别：" prop="sex" required>
                            <el-radio-group v-model="queryForm.sex">
                                <el-radio-button
                                    v-for="item in nj_sex"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="进入时间：" prop="checkintime" required>
                            <el-date-picker
                                v-model="queryForm.checkintime"
                                placeholder="请选择来访时间"
                                style="width: 100%"
                                type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                            />
                        </el-form-item>
                        <el-row :gutter="24">
                            <el-col :span="17">
                                <el-form-item label="身份证：" prop="sfzId">
                                    <el-input
                                        v-model="queryForm.sfzId"
                                        placeholder="请填写来访人身份证"
                                        @change="idCardChangeHandle"
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col :span="3">
                                <!-- @click="visitHistoryRef.showVisitHistory(queryForm.sfzId)" -->
                                <el-button
                                    :disabled="viewHistoryDisable"
                                    type="primary"
                                    @click="showVisitHistory(queryForm.sfzId)"
                                >
                                    历史信访记录
                                </el-button>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </template>
            <template v-else>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="姓名：" prop="name" required>
                            <el-input v-model="queryForm.name" placeholder="请填写来访姓名"/>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="性别：" prop="sex" required>
                            <el-radio-group v-model="queryForm.sex">
                                <el-radio-button
                                    v-for="item in nj_sex"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="进入时间：" prop="checkintime" required>
                            <el-date-picker
                                v-model="queryForm.checkintime"
                                placeholder="请选择来访时间"
                                style="width: 100%"
                                type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-row :gutter="24">
                            <el-col :span="17">
                                <el-form-item label="身份证：" prop="sfzId">
                                    <el-input
                                        v-model="queryForm.sfzId"
                                        placeholder="请填写来访人身份证"
                                        @change="idCardChangeHandle"
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col :span="3">
                                <el-button
                                    :disabled="viewHistoryDisable"
                                    type="primary"
                                    @click="visitHistoryRef.showVisitHistory(queryForm.sfzId)"
                                >
                                    历史信访记录
                                </el-button>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </template>

            <div class="my-2"></div>

            <DividerHeader title="来访信息"/>

            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="关注级别：" prop="alertlever" required>
                        <el-radio-group v-model="queryForm.alertlever">
                            <el-radio-button
                                v-for="item in nj_laifang_color"
                                :key="item.value"
                                :class="item.elTagClass"
                                :label="item.label"
                                :value="item.value"
                            ></el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="来访事由：" prop="checkinreason" required>
                        <el-radio-group v-model="queryForm.checkinreason">
                            <el-radio-button
                                v-for="item in nj_checkinreason"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="警务区：" prop="policeareaId" required>
                        <PoliceAreaManageSelect v-model="queryForm.policeareaId"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="访问部门：">
                        <el-input v-model="queryForm.checkindepartment" placeholder="请填写访问部门"/>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="安检情况：" label-position="top" prop="checkinfo" required>
                        <el-input
                            v-model="queryForm.checkinfo"
                            :autosize="{ minRows: isEdit ? 1 : 3, maxRows: 9999}" placeholder="请填写安检情况"
                            type="textarea"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="来访者地址：" label-position="top">
                        <el-input
                            v-model="queryForm.address"
                            :autosize="{ minRows: isEdit ? 1 : 3, maxRows: 9999}"
                            placeholder="请填写来访者地址"
                            type="textarea"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="寄存物品：" label-position="top">
                        <el-input
                            v-model="queryForm.goods"
                            :autosize="{ minRows: isEdit ? 1 : 3, maxRows: 9999}"
                            placeholder="请填写寄存物品"
                            type="textarea"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="信访情况：" label-position="top">
                        <el-input
                            v-model="queryForm.checkininfo"
                            :autosize="{ minRows: isEdit ? 1 : 3, maxRows: 9999}"
                            placeholder="请填写信访情况"
                            type="textarea"
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <div class="my-1"></div>

            <DividerHeader title="预案信息"/>
            <el-form-item label="处理预案：">
                <PlanManageSelect
                    ref="planManageSelectRef"
                    v-model="queryForm.yuanId"
                    @planDetail="getPlanDetail"
                />
            </el-form-item>
            <el-form-item>
                <el-input
                    v-model="measure"
                    :autosize="{ minRows: isEdit ? 1 : 2, maxRows: 9999}"
                    disabled
                    type="textarea"
                />
            </el-form-item>
        </el-form>

        <template v-if="showHistoryVisitStatus">
            <DividerHeader title="历史信访记录"/>
            <el-alert :closable="false" :title="historyTitle" class="mb-2" type="success"/>
            <el-table
                v-loading="loading"
                :data="visitHistoryTableData"
                border
                show-overflow-tooltip
            >
                <el-table-column type="index"/>
                <el-table-column label="接待单位" prop="unitName"/>
                <el-table-column label="接待场所" prop="policeareaId"/>
                <el-table-column label="执勤法警" prop="adduserId"/>
                <el-table-column label="来访人" prop="name"/>
                <el-table-column label="来访日期" prop="checkintime"/>
                <el-table-column label="信访情况" prop="checkininfo"/>
            </el-table>
        </template>
        <template #footer>
            <el-button v-if="queryForm.photourl" type="primary" @click="addKeyPersonManage()">
                添加重点人员
            </el-button>

            <!-- 更新 -->
            <el-button v-if="isEdit" type="primary" @click="updatePlanHandle(queryFormRef)">更新</el-button>
            <!-- 创建 -->
            <el-button v-else type="primary" @click="createPlanHandle(queryFormRef)">提交</el-button>
            <el-button @click="changeShowStatus">关闭</el-button>
        </template>
    </el-drawer>
    <!--    <VisitHistory ref="visitHistoryRef"/>-->
</template>

<script setup>
import {useTemplateRef} from 'vue';
import PlanManageSelect from '@/components/PlanManageSelect/PlanManageSelect.vue';
import {getPlanInfo} from '@/api/PlanManage/Plan.js';
import PoliceAreaManageSelect from '@/components/PoliceAreaManageSelect/PoliceAreaManageSelect.vue';
import {
    createVisitApi,
    getVisitDetailApi,
    getVisitHistoryApi,
    updateVisitApi
} from '@/api/RegisterVisit/RegisterVisit.js';
import DividerHeader from '@/components/DividerHeader/DividerHeader.vue';
import {
    createKeyPersonManage,
    getKeyPersonManageList,
    getKeyPersonManageListNoLimit
} from '@/api/PlanManage/KeyPersonManage.js';
import {ElMessage, ElMessageBox} from 'element-plus';
import dayjs from 'dayjs';

const {proxy} = getCurrentInstance()
const {nj_laifang_color, nj_sex, nj_checkinreason} = proxy.useDict('nj_laifang_color', 'nj_sex', 'nj_checkinreason')

defineOptions({
    name: 'AddEditRegisterVisit'
})

const emit = defineEmits(['refresh-list'])

// 抽屉显示状态
const isShow = ref(false);
// 抽屉标题
const title = ref('来访登记');
// 预案处置方案
const measure = ref('');
// 是否显示历史来访记录
const isVisitHistory = ref(false);
// 是否是编辑模式
const isEdit = ref(false)
// 重点人员的 ID
const personnelId = ref('')

const defaultQueryForm = {
    // 姓名
    name: '',
    // 进入时间
    checkintime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    // // 身份证
    // sfzId: '',
    // 关注级别
    alertlever: '1',
    // 警务区
    policeareaId: '',
    // 性别
    sex: '1',
    // 来访事由
    checkinreason: '1',
    // 安检情况
    checkinfo: '正常',
    // 来访者地址
    address: '',
    // 寄存物品
    goods: '',
    // 信访情况
    checkininfo: '',
    // 处理预案
    yuanId: '',
    // 访问部门
    checkindepartment: '',
    // 照片
    photourl: ''
}
const queryForm = ref({...defaultQueryForm});
const queryFormRules = reactive({
    name: {
        required: true, message: '请填写来访人姓名', trigger: 'blur'
    },
    checkintime: {
        required: true, message: '请选择来访时间', trigger: 'blur'
    },
    // sfzId: [
    //     {required: true, message: '请填写来访人身份证', trigger: 'blur'},
    //     {min: 1, max: 19, message: '请输入18位身份证号'}
    //     // {
    //     //     validator: (rule, value, callback) => {
    //     //         if (!value) {
    //     //             callback(new Error('请填写身份证号'));
    //     //             viewHistoryDisable.value = true;
    //     //         } else if (!/^\d{17}(\d|X|x)$/.test(value)) {
    //     //             callback(new Error('请输入正确的身份证号'));
    //     //             viewHistoryDisable.value = true;
    //     //         } else {
    //     //             callback(); // 验证通过
    //     //             viewHistoryDisable.value = false;
    //     //         }
    //     //     }, trigger: 'blur'
    //     // }
    // ],
    policeareaId: {
        required: true, message: '请选择警务区', trigger: 'blur'
    },
    sex: {
        required: true, message: '请选择性别', trigger: 'blur'
    },
    checkinreason: {
        required: true, message: '请选择来访事由', trigger: 'blur'
    },
    checkinfo: {
        required: true, message: '请填写安检情况', trigger: 'blur'
    }
});

// 来访登记 ID
const visitId = ref('')

// 控制查看历史数据按钮状态
const viewHistoryDisable = ref(true)

const showHistoryVisitStatus = ref(false)
const loading = ref(false)
const historyTitle = ref('')
const visitHistoryTableData = ref([])

// 变更显示状态
const changeShowStatus = () => {
    isShow.value = !isShow.value
    if (!isShow.value) {
        queryForm.value = {...defaultQueryForm};
        measure.value = '';
        isEdit.value = false;
        isVisitHistory.value = false;
        viewHistoryDisable.value = true;
        showHistoryVisitStatus.value = false;
        visitHistoryTableData.value = []
    }
}

// 显示新增来访登记抽屉
const showAddRegisterVisit = () => {
    changeShowStatus()
}

// 显示编辑来访登记抽屉
const showEditRegisterVisit = async (id) => {
    changeShowStatus()
    visitId.value = id;
    isEdit.value = true;
    await getDetail()

    await checkSubmitKeyStatus().catch((err) => {
        ElMessage.error(`${err['name']}被${err['unitId']}列为重点人员 ，请密切关切。`)
    })
}

defineExpose({showAddRegisterVisit, showEditRegisterVisit});

const queryFormRef = useTemplateRef('queryFormRef')
const visitHistoryRef = useTemplateRef('visitHistoryRef')
const planManageSelectRef = useTemplateRef('planManageSelectRef')

// 创建新的来访记录
const createPlanHandle = async (elForm) => {
    if (!elForm) return
    await elForm.validate(async (valid, fields) => {
        if (valid) {
            if (!queryForm.value.sfzId) {
                delete queryForm.value.sfzId;
            }
            await createVisitApi(queryForm.value)
            changeShowStatus()
            emit('refresh-list')
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 更新来访记录
const updatePlanHandle = async (elForm) => {
    if (!elForm) return
    await elForm.validate(async (valid, fields) => {
        if (valid) {
            if (!queryForm.value.sfzId) {
                delete queryForm.value.sfzId;
            }
            await updateVisitApi(queryForm.value)
            changeShowStatus()
            emit('refresh-list')
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 获取预案详情
const getPlanDetail = async (queryId) => {
    if (!queryId) {
        measure.value = ''
        return;
    }
    const res = await getPlanInfo(queryId);
    measure.value = res.data.measure;
}

// 获取来访登记详情
const getDetail = async () => {
    const res = await getVisitDetailApi(visitId.value)
    queryForm.value = res.data

    // 检测来访登记进入时间是否为空，空则加入当前时间，修补小乌龟终端无时间写入
    if (!res.data.checkintime) {
        queryForm.value.checkintime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    }

    if (res.data.yuanId) {
        await getPlanDetail(res.data.yuanId)
    }
    if (res.data.sfzId) {
        viewHistoryDisable.value = false;
        await validateUserHasPlan()
    }
}

// 身份证输入框失去焦点后的事件
const idCardChangeHandle = async (value) => {
    viewHistoryDisable.value = !value;
    await validateUserHasPlan()
}

// 校验用户是否有预案
const validateUserHasPlan = async () => {
    const res = await getKeyPersonManageList({
        idnumber: queryForm.value.sfzId
    });

    if (res.rows.length >= 1) {
        personnelId.value = res.rows[0].peopleId
        await planManageSelectRef.value.listenHasPersonnelId(personnelId.value)
    } else {
        personnelId.value = ''
    }
}

// 添加重点人员
const addKeyPersonManage = async () => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确定将此人添加至重点对象管理?',
            '',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'success',
            }
        );

        if (confirmResult !== 'confirm') return;

        const submitStatus = await checkSubmitKeyStatus();

        const personData = {
            idnumber: queryForm.value.sfzId,
            name: queryForm.value.name,
            sex: queryForm.value.sex,
            warninglevel: '1', // 预警级别
            state: '0', // 状态
            photo: queryForm.value.photourl // 图片地址
        };

        await createKeyPersonManage(personData);
        ElMessage.success('添加成功');
    } catch (err) {
        ElMessage.error('当前人员已在重点人员观测数据中，请勿重复添加。');
    }

}

// 检测是否可以添加重点人员
const checkSubmitKeyStatus = async () => {
    const res = await getKeyPersonManageListNoLimit({
        idnumber: queryForm.value.sfzId
    })

    return new Promise((resolve, reject) => {
        if (res.total === 0) {
            return resolve(true)
        }

        return reject(res.rows[0])
    })
}

const showVisitHistory = async (sfzId) => {
    showHistoryVisitStatus.value = !showHistoryVisitStatus.value;

    loading.value = true;
    const res = await getVisitHistoryApi({
        sfzId: sfzId
    })
    // total.value = res.data;
    visitHistoryTableData.value = res.data;
    historyTitle.value = `共计 [ ${res.data.length} ] 次来访记录`
    loading.value = false;
}
</script>

<style lang="scss">
.image__error .el-image {
    --img-height: 12.5rem;
    background: var(--el-fill-color-light);
    padding: 0 5px;
    max-width: 100%;
    max-height: var(--img-height);
    width: 100%;
    height: var(--img-height);
    border-radius: 5px;

    img {
        object-fit: contain;
    }
}

.image__error .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
}

.image__error .image-slot .el-icon {
    font-size: 30px;
}

$colors: (
    green: #008000,
    blue: #0000ff,
    yellow: yellow,
    orange: orange,
    red: red
);

@each $name, $color in $colors {
    //.el-radio-button.#{$name} {
    //    .el-radio-button__inner {
    //        --diy-color: #{$color};
    //        --el-border-color: var(--diy-color);
    //        background: var(--diy-color);
    //        border-color: var(--diy-color);
    //
    //        @if $name == yellow {
    //            color: var(--el-text-color-regular);
    //        } @else {
    //            color: var(--el-fill-color-blank);
    //        }
    //    }
    //}
    .el-radio-button.#{$name}.is-active .el-radio-button__original-radio:not(:disabled) + .el-radio-button__inner {
        --diy-color: #{$color};
        background-color: var(--diy-color);
        border-color: var(--el-border-color);
        box-shadow: -1px 0 0 0 var(--el-border-color);
        @if $name == yellow {
            color: var(--el-text-color-regular);
        }
        //@else {
        //            color: var(--el-fill-color-blank);
        //        }
    }
}

//.el-radio-button.blue.is-active .el-radio-button__original-radio:not(:disabled) + .el-radio-button__inner {
//    background-color: blue;
//    border-color: blue;
//}
</style>